package com.lmpop.createIndex.searchModel;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;

public class CreateModel
{
  public int num = 0;
  LinkInterf linkInterf;
  String rootpath = "";

  public CreateModel() {
    this.linkInterf = new LinkInterf();
    this.rootpath = this.linkInterf.getConfigString("rootpath");
  }

  public void createIndex(String saveDir, String sql)
  {
	  
	//advinfo=/data/index/advinfo|
  	//select f.*,a.file_path from ti_advinfo f left join ti_attach a 
  	//on f.adv_id \= a.attach_root_id  
  	//WHERE TO_DAYS(start_date)<TO_DAYS(NOW()) AND TO_DAYS(end_date)>TO_DAYS(NOW())
    saveDir = this.rootpath + saveDir;

    File INDEX_DIR = new File(saveDir);
    try
    {
      IndexWriter writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), true);
      indexDocs(writer, sql);
      writer.optimize();
      writer.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
      System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
    }
  }

  public void indexDocs(IndexWriter writer, String sql)throws IOException
  {
    Connection con = null;
    con = this.linkInterf.getConnection();
    Statement stm = null;
    ResultSet rst = null;
    try
    {
      stm = con.createStatement();
      rst = stm.executeQuery(sql);
      joinIndexFile(writer, rst);
      rst.close();
      stm.close();
      con.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    finally {
      try {
        if ((con != null) && (!con.isClosed())) con.close(); 
      }
      catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }

  private void joinIndexFile(IndexWriter writer, ResultSet rst)
  {
    ResultSetMetaData rstMetaDate = null;
    int columnCount = 0;
    try
    {
      rstMetaDate = rst.getMetaData();
      columnCount = rstMetaDate.getColumnCount();
      int rstCount = 0;
      while (rst.next())
      {
        rstCount++;
        addDoc(rst, writer, columnCount, rstMetaDate);
      }

      if (rstCount == 0) {
        addDoc(null, writer, columnCount, rstMetaDate);
      }

    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public void addDoc(ResultSet rst, IndexWriter writer, int columnCount, ResultSetMetaData rstMetaDate) throws SQLException, IOException {
    Document doc = new Document();
    for (int i = 1; i <= columnCount; i++) {
      String strFieldName = rstMetaDate.getColumnName(i).toLowerCase();
      String fieldNameValue = "0";
      if ((rst != null) && (rst.getObject(i) != null)) {
        fieldNameValue = rst.getObject(i).toString();
      }
      doc.add(new Field(strFieldName, fieldNameValue, Field.Store.YES, Field.Index.TOKENIZED));

      if ((rstMetaDate.getColumnTypeName(i).toLowerCase().equals("decimal")) && (fieldNameValue.indexOf(".") > -1)) {
        dealDecimal(fieldNameValue, i, strFieldName, doc);
      }
    }
    doc.add(new Field("all", "allinfo", Field.Store.YES, Field.Index.TOKENIZED));
    writer.addDocument(doc);
    this.num += 1;
  }

  public String formatStr(String str)
  {
    if (str.equals("")) return "";
    str = str.trim();
    str = str.replaceAll("\\&[a-zA-Z]{1,10};", "");
    str = str.replaceAll("<[^>]*>", "");
    str = str.replaceAll("[(>)<]", "");
    if (str.length() > 150)
    {
      str = str.substring(0, 150);
    }
    return str;
  }

  public void dealDecimal(String fieldNameValue, int i, String strFieldName, Document doc) throws SQLException {
    fieldNameValue = fieldNameValue.substring(0, fieldNameValue.indexOf("."));
    int fieldValueLen = fieldNameValue.length();
    String zeroNum = "";
    int extendsNum = 10;
    if (fieldValueLen < extendsNum) {
      int addNum = extendsNum - fieldValueLen;
      for (int j = 0; j < addNum; j++) {
        zeroNum = zeroNum + "0";
      }
    }
    fieldNameValue = zeroNum + fieldNameValue;
    doc.add(new Field("_" + strFieldName, fieldNameValue, Field.Store.YES, Field.Index.TOKENIZED));
  }
}